<template>

  <div class="app-container">
    <el-aside style="padding-right: 10px; padding-left: 15px; padding-top: 0px;float:left;width:16%;height:100%;background:none;">
      <div class="block" style="width:100%;height:100%;background-color: #FFF;">
        <el-tree
          id="el-tree"
          ref="tree"
          class="filter-tree"
          :data="dicts"
          node-key="id"
          :highlight-current="true"
          default-expand-all
          :props="defaultProps"
          @node-click="handleNodeClick"
          @node-contextmenu="rightClick"
        />
        <div v-show="menu0Visible">
          <ul id="menu0" class="menu">
            <li id="menu_item" class="el-icon-circle-plus-outline" @click="handleAdd">&nbsp;新增项目</li>
          </ul>
        </div>
      </div>
    </el-aside>
    <el-aside style="padding-right: 5px; padding-left: 5px; padding-top: 0px;float:left;width:84%;background:none;">
      <div id="filter-container" class="filter-container" style="float:left;">
        <el-select v-model="queryPage.status" class="filter-item" placeholder="状态" style="width: 150px" clearable>
          <el-option v-for="item in ywTypes" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-input v-model="queryPage.name" class="filter-item" placeholder="项目名称" style="width: 150px" clearable />

        <el-button class="filter-item" icon="el-icon-search" type="primary" @click="search()">
          查询
        </el-button>
      </div>

      <div style="float:right;">
        <el-button type="primary" icon="el-icon-circle-check" @click="handleSubmit">提交</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleRemove">删除</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleComplete">中止</el-button>
      </div>

      <el-table v-loading="listLoading" :data="data" :height="tableHeight4" style="width: 100%;margin-top: 5px; overflow:auto" border @selection-change="handleSelectionChange">
        <el-table-column type="index" :index="indexMethod" header-align="center" align="center" label="序号" width="60px" />
        <el-table-column type="selection" header-align="center" align="left" />
        <el-table-column header-align="center" align="left" label="操作" width="200px" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="['1','4','5'].includes(scope.row.status)" type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
            <el-button v-if="!['1','2'].includes(scope.row.status)" type="primary" size="small" @click="handleView(scope)">审核记录</el-button>
            <el-button v-if="scope.row.status === '3'" type="primary" size="small" @click="handleDownload(scope)">文件下载</el-button>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="right" label="编号" width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.sortNum }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.xiangmumingcheng }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="项目类型" width="150px">
          <template slot-scope="scope">
            <span>{{ getDicName(scope.row.type,'CDS_XIANGMU_TYPE') }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="项目目录模型" width="240px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.catalogName }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="是否展示api" width="120px">
          <template slot-scope="scope">
            <span>{{ getDicName(scope.row.ifzs,'CDS_YON') }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="状态" width="100px">
          <template slot-scope="scope">
            <span>{{ getDicName(scope.row.status,'CDS_YEWU_STATUS') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="dialogAddVisible" append-to-body width="800px" :show-close="false" :title="'新增项目'" :close-on-click-modal="false">
        <dialog-add v-if="dialogAddVisible" ref="dialogAdd" :proid="code" :visible.sync="dialogAddVisible" />
      </el-dialog>

      <el-dialog :visible.sync="dialogEditVisible" append-to-body width="800px" :show-close="false" :title="'编辑项目'" :close-on-click-modal="false">
        <dialog-edit v-if="dialogEditVisible" ref="dialogEdit" :proid="code" :visible.sync="dialogEditVisible" />
      </el-dialog>

      <el-dialog :visible.sync="dialogViewVisible" append-to-body width="800px" :title="'审核记录'" :close-on-click-modal="false">
        <dialog-view v-if="dialogViewVisible" ref="dialogView" :proid="code" :visible.sync="dialogViewVisible" />
      </el-dialog>

      <pagination v-show="total>-1" :total="total" :page.sync="queryPage.page" :limit.sync="queryPage.limit" @pagination="loadList" />

    </el-aside>
  </div>
</template>

<script>
import { getList, remove, complete, submit, getXiangMuTypes, downloadFile } from '@/api/projectInfo'
import { getDictListByCode } from '@/api/dict'
import { Message, MessageBox } from 'element-ui'
import { tableHeight4 } from '@/utils/tableHeight'
import Pagination from '@/components/Pagination'

import DialogAdd from './add' // eslint-disable-line no-unused-vars
import DialogEdit from './edit' // eslint-disable-line no-unused-vars
import DialogView from './view' // eslint-disable-line no-unused-vars

export default {
  components: { Pagination, DialogAdd, DialogEdit, DialogView },
  mixins: [tableHeight4],
  provide() {
    return {
      onLoadList: this.loadList
    }
  },
  data() {
    return {
      listLoading: false,
      queryPage: {
        page: 1,
        limit: 20
      },
      total: 0,
      code: '',
      data: [],
      dialogAddVisible: false,
      dialogEditVisible: false,
      dialogViewVisible: false,
      ywTypes: [],
      xmTypes: [],
      ynTypes: [],
      multipleSelection: [],
      dicts: [],
      defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      selectNode: {
        'id': 1
      }, // 记录当前点击节点
      DATA: null, // 记录右键点击节点对象数据
      NODE: null, // 记录右键点击节点
      menu0Visible: false // 右键菜单--应用右键菜单显示
    }
  },
  created() {
    this.getDictList('CDS_XIANGMU_TYPE')
    this.getDictList('CDS_YEWU_STATUS')
    this.getDictList('CDS_YON')
    this.loadList()
    this.getXiangMuTypeList()
  },
  methods: {
    indexMethod(index) {
      return (index + 1) + (this.queryPage.page - 1) * this.queryPage.limit
    },
    getXiangMuTypeList() {
      getXiangMuTypes().then(response => {
        this.dicts = response.data
      })
    },
    // 点击节点，1：展开/关闭下级节点；2：查询右面列表数据
    handleNodeClick(data, node, e) {
      // 关闭右键弹出框
      this.menu0Visible = false
      // 记录当前选择节点
      this.selectNode = data
      this.selectNode.level = node.level
      // 根据选择节点获取值
      this.loadList()
    },
    // 右键点击
    rightClick(MouseEvent, object, Node, element) { // 鼠标右击触发事件 鼠标点击事件 对象（数据） 节点 元素
      this.DATA = object
      this.state = object.status
      this.NODE = Node
      if (this.NODE.level === 2) { // 应用 -- 可以创建分组
        // // 显示弹窗0
        this.menu0Visible = true // 显示模态窗口，跳出自定义菜单栏
        var menu0 = document.querySelector('#menu0')
        document.addEventListener('click', this.foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
        menu0.style.display = 'block'
        menu0.style.left = MouseEvent.clientX + 30 + 'px' // 右键弹出框横向位置
        menu0.style.top = MouseEvent.clientY - 20 + 'px' // 右键弹出框纵向位置
      }
    },
    // 取消鼠标监听事件 菜单栏
    foo() {
      this.menu0Visible = false
      document.removeEventListener('click', this.foo) // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
    },
    getDictList(code) {
      getDictListByCode(code).then(response => {
        if (code === 'CDS_XIANGMU_TYPE') {
          this.xmTypes = response.data
        }
        if (code === 'CDS_YEWU_STATUS') {
          this.ywTypes = response.data
        }
        if (code === 'CDS_YON') {
          this.ynTypes = response.data
        }
      })
    },
    getDicName(code, flag) {
      var dict = null
      if (flag === 'CDS_XIANGMU_TYPE') {
        dict = this.xmTypes
      } else if (flag === 'CDS_YEWU_STATUS') {
        dict = this.ywTypes
      } else if (flag === 'CDS_YON') {
        dict = this.ynTypes
      }
      for (var i in dict) {
        if (dict[i].code === code) {
          return dict[i].name
        }
      }
    },
    search() { // 查询
      this.loadList()
    },
    loadList() { // 加载列表
      this.data = []
      this.listLoading = true

      this.queryPage.level = this.selectNode.level
      this.queryPage.type = this.selectNode.id
      getList(this.queryPage).then(response => {
        const { data } = response

        this.data = data.records
        this.total = parseInt(data.total)
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    handleAdd() {
      this.dialogAddVisible = true
      this.code = this.DATA.id
      this.$nextTick(() => {
        this.$refs.dialogAdd
      })
    },
    handleEdit(scope) {
      this.dialogEditVisible = true
      this.code = scope.row.id
      this.$nextTick(() => {
        this.$refs.dialogEdit
        this.$refs.dialogEdit.getDetailed()
      })
    },
    handleView(scope) {
      this.dialogViewVisible = true
      this.code = scope.row.id
      this.$nextTick(() => {
        this.$refs.dialogView
        this.$refs.dialogView.getDetailed()
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = []
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i])
      }
    },
    handleRemove() {
      if (this.multipleSelection.length === 0) {
        Message({
          message: '至少选择一条数据',
          type: 'error',
          duration: 2 * 1000
        })
        return
      }
      var flag = 0
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        for (var i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].status !== '1') {
            flag = 1
            break
          }
        }
        if (flag !== 0) {
          Message({
            message: '不可以选择非保存状态的项目进行删除！',
            type: 'error',
            duration: 2 * 1000
          })
          return
        }
      }
      MessageBox.confirm('确认删除', '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '删除中......',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        var ids = this.multipleSelection.map(item => item.id).join()// 获取所有选中行的id组成的字符串，以逗号分隔
        remove({ ids: ids }).then(response => {
          Message({
            message: '删除成功',
            type: 'success',
            duration: 5 * 1000
          })
          loading.close()
          // 重新加载表格
          this.loadList()
        })
      })
    },
    handleComplete() {
      if (this.multipleSelection.length === 0) {
        Message({
          message: '至少选择一条数据',
          type: 'error',
          duration: 2 * 1000
        })
        return
      }
      MessageBox.confirm('确认中止', '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '中止中......',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        var ids = this.multipleSelection.map(item => item.id).join()// 获取所有选中行的id组成的字符串，以逗号分隔
        complete({ ids: ids }).then(response => {
          Message({
            message: '中止成功',
            type: 'success',
            duration: 5 * 1000
          })
          loading.close()
          // 重新加载表格
          this.loadList()
        }).catch(response => {
          loading.close()
          this.loadList()
        })
      })
    },
    handleSubmit() {
      if (this.multipleSelection.length === 0) {
        Message({
          message: '至少选择一条数据',
          type: 'error',
          duration: 2 * 1000
        })
        return
      }
      var flag = 0
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        for (var i = 0; i < this.multipleSelection.length; i++) {
          if (this.multipleSelection[i].status !== '1') {
            flag = 1
            break
          }
        }
        if (flag !== 0) {
          Message({
            message: '只可以选择保存状态的项目进行提交！',
            type: 'error',
            duration: 2 * 1000
          })
          return
        }
      }
      MessageBox.confirm('确认提交', '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '提交中......',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        var ids = this.multipleSelection.map(item => item.id).join()// 获取所有选中行的id组成的字符串，以逗号分隔
        submit({ ids: ids }).then(response => {
          Message({
            message: '提交成功',
            type: 'success',
            duration: 5 * 1000
          })
          loading.close()
          // 重新加载表格
          this.loadList()
        }).catch(response => {
          loading.close()
          this.loadList()
        })
      })
    },
    handleDownload(scope) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      downloadFile({ id: scope.row.id }).then(response => {
        var fileName = scope.row.xiangmumingcheng + '.zip'
        const contentDisposition = response.headers['content-disposition']
        if (contentDisposition) {
          fileName = window.decodeURI(response.headers['content-disposition'].split('=')[1], 'UTF-8')
        }

        const blob = new Blob([response.data], {
          type: `application/zip` // word文档为msword,pdf文档为pdf
        })
        const objectUrl = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = objectUrl
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        // 释放内存
        window.URL.revokeObjectURL(link.href)
        loading.close()
      }).catch(response => {
        loading.close()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.app-container{
  padding:10px 20px;
}
.filter-container {
  padding-bottom: 10px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  .date-filter-item{
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
.pagination-container {
  margin-top: 0 !important;
  padding: 10px 16px !important;
}
</style>

<style scoped>
.menu {
  width: 120px;
  line-height: 30px;
  position: fixed;
  border: 1px solid #ccc;
  font-size: 14px;
  font-family: "黑体";
  color: #474a4d;
  font-weight: 100;
  background-color: white;
  list-style: none;
  padding-left: 10px;
  z-index: 999;
}
</style>
